package com.gel.springai.redis.starter;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/*自动配置类*/
//指定该自动配置在Redis自动配置之后执行
@AutoConfiguration(after = RedisAutoConfiguration.class)
//只有当类路径中存在RedisTemplate和ChatMemory类时才启用该配置
@ConditionalOnClass({RedisTemplate.class, ChatMemory.class})
//只有当配置属性spring.ai.chat.memory.redis.enabled=true时启用，如果没有配置则默认启用
@ConditionalOnProperty(prefix = "spring.ai.chat.memory.redis", name = "enabled", havingValue = "true", matchIfMissing = true)
public class RedisChatMemoryAutoConfiguration {


    @Bean
    @ConditionalOnMissingBean(name = "springAiRedisTemplate")
    public RedisTemplate<String, SerializableMessage>
    springAiRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, SerializableMessage> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 配置支持多态的 Jackson 序列化器
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.activateDefaultTyping(
                objectMapper.getPolymorphicTypeValidator(),
                ObjectMapper.DefaultTyping.EVERYTHING,
                JsonTypeInfo.As.PROPERTY
        );

        GenericJackson2JsonRedisSerializer serializer =
                new GenericJackson2JsonRedisSerializer(objectMapper);
        //配置序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(ChatMemory.class)
    public ChatMemory redisChatMemory(RedisTemplate<String, SerializableMessage> redisTemplate) {
        return new RedisChatMemory(redisTemplate);
    }
}
